import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import EditorView from '../views/EditorView.vue'
import DebugEditorView from '../views/DebugEditorView.vue'
import LoginView from '../views/LoginView.vue'
import PreviewView from '../views/PreviewView.vue'
import TopicWorkspaceView from '../views/TopicWorkspaceView.vue'

// 路由守卫
const isAuthenticated = () => {
  const user = localStorage.getItem('user')
  return user !== null
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/',
      name: 'home',
      component: HomeView,
      beforeEnter: (to, from, next) => {
        if (!isAuthenticated()) {
          next('/login')
        } else {
          next()
        }
      }
    },
    {
      path: '/editor',
      name: 'editor',
      component: EditorView,
      beforeEnter: (to, from, next) => {
        if (!isAuthenticated()) {
          next('/login')
        } else {
          next()
        }
      }
    },
    {
      path: '/debug-editor',
      name: 'debug-editor',
      component: DebugEditorView,
      beforeEnter: (to, from, next) => {
        if (!isAuthenticated()) {
          next('/login')
        } else {
          next()
        }
      }
    },
    {
      path: '/topic/:topicId',
      name: 'topic-workspace',
      component: TopicWorkspaceView,
      beforeEnter: (to, from, next) => {
        if (!isAuthenticated()) {
          next('/login')
        } else {
          next()
        }
      }
    },
    {
      path: '/preview',
      name: 'preview',
      component: PreviewView,
      beforeEnter: (to, from, next) => {
        if (!isAuthenticated()) {
          next('/login')
        } else {
          next()
        }
      }
    }
  ]
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  if (to.name !== 'login' && !isAuthenticated()) {
    next('/login')
  } else {
    next()
  }
})

export default router